﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using crm_library.DataAccess.TableReps;
using System.IO;

namespace crm_library.DataAccess
{
	/// <summary>
	/// Enables generic conversions between XML Strings and ObjectRepresentations.
	/// </summary>
	public static class XMLPipe
	{
		/// <summary>
		/// Generic method to Deserialize an ObjectRepresentation to XML
		/// </summary>
		/// <typeparam name="T">Type of ObjectRepresentation to Deserialize</typeparam>
		/// <param name="destination">ObjectRepresentation to Deserialize.</param>
		/// <param name="sourceXml">Source XML to Deserialize from.</param>
		/// <returns>Filled Object</returns>
		public static T XMLToObject<T>(T destination, string sourceXml) where T : ObjectRepresentation
		{
			var serializer = new XmlSerializer(typeof(T));
			return (T)serializer.Deserialize(new StringReader(sourceXml));
		}

		/// <summary>
		/// Generic method to Serialize an ObjectRepresentation from XML
		/// </summary>
		/// <typeparam name="T">Type of ObjectRepresentation to Serialize</typeparam>
		/// <param name="source">ObjectRepresentation to Serialize</param>
		/// <returns>XML string</returns>
		public static string ObjectToXML<T>(T source) where T : ObjectRepresentation
		{
			var serializer = new XmlSerializer(typeof(T));
			StringWriter writer = new StringWriter();
			serializer.Serialize(writer, source);
			return writer.ToString();
		}
	}
}
